package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.threadlocal.WmThreadLocalUtils;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 *
 */
@Slf4j
@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper,WmMaterial> implements WmMaterialService {

    @Value("${file.oss.profix}")
    String profix;
    @Value("${file.oss.endpoint}")
    String endpoint;
    @Value("${file.oss.web-site}")
    String webSite;

    @Autowired
    FileStorageService fileStorageService;

    @Override
    public ResponseResult<WmMaterial> uploadPicture(MultipartFile multipartFile) {
        // 图片上传
        // 检查参数
        if (multipartFile == null || multipartFile.getSize() == 0){
            throw new CustomException(AppHttpCodeEnum.FILE_UPLOAD_PARAMREQUIRE_ERROR);
        }

        String store = null;
        try {
            // 上传到oss
            // 生成文件名
            String fileName = UUID.randomUUID().toString().replace("-", "");
            // 获取后缀名
            String originalFilename = multipartFile.getOriginalFilename();
            String sufix = originalFilename.substring(originalFilename.lastIndexOf("."));
            // 上传文件
            // 返回值为全路径
            store = fileStorageService.store(profix, fileName + sufix, multipartFile.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
            log.error("WmMaterialServiceImpl uploadPicture error: {}", e);
            throw new CustomException(AppHttpCodeEnum.FILE_UPLOAD_ERROR);
        }
        // 保存到数据库
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setCreatedTime(new Date());
        wmMaterial.setIsCollection((short)0);
        wmMaterial.setType((short)0);
        wmMaterial.setUrl(store);
        // 通过ThreadLocal获取用户信息
        WmUser user = WmThreadLocalUtils.getUser();
        wmMaterial.setUserId(user.getId());
        // 保存
        save(wmMaterial);
        // 返回前端
        wmMaterial.setUrl(webSite+store);
        return ResponseResult.okResult(wmMaterial);
    }

    @Override
    public ResponseResult findList(WmMaterialDto dto) {
        // 检查参数
        if (dto == null){
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        dto.checkParam();
        Page<WmMaterial> page = new Page<>(dto.getPage(),dto.getSize());
        LambdaQueryWrapper<WmMaterial> wrapper = new LambdaQueryWrapper<>();
        // 当前用户为查询条件
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null){
            throw new CustomException(AppHttpCodeEnum.USER_NOT_EXIST);
        }
        wrapper.eq(WmMaterial::getUserId, user.getId());
        // 是否收藏
        if (dto.getIsCollection() == 1){
            wrapper.eq(WmMaterial::getIsCollection,dto.getIsCollection());
        }
        wrapper.orderByDesc(WmMaterial::getCreatedTime);
        // 按照发布时间降序排序
        IPage<WmMaterial> pageResult = page(page, wrapper);
        // 处理图片
        List<WmMaterial> records = pageResult.getRecords();
        for (WmMaterial record : records) {
            record.setUrl(webSite+record.getUrl());
        }
        // 封装分页结果
        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) pageResult.getTotal());
        pageResponseResult.setData(records);
        return pageResponseResult;
    }
    @Autowired
    WmNewsMaterialMapper wmNewsMaterialMapper;
    @Override
    public ResponseResult delPicture(Integer id) {
        // 根据id删除素材
        // 如果该图片已经被引用则不能被删除
        // 检查参数
        if (id == null){
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        // 根据获取引用信息
        WmMaterial wmMaterial = getById(id);

        Integer wmNewsMaterial = wmNewsMaterialMapper.selectCount(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getMaterialId, wmMaterial.getId()));

        if (wmNewsMaterial > 0){
            throw new CustomException(AppHttpCodeEnum.NO_OPERATOR_AUTH,"该图片已被引用，无法删除");
        }

        removeById(id);

        // oss删除文件
        fileStorageService.delete(wmMaterial.getUrl());

        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult updateStatus(Integer id, Short type) {
        // 检查参数
        if (id == null){
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        // 获取当前用户状态
//        WmUser user = WmThreadLocalUtils.getUser();
//        Integer userId = user.getId();
//
        // 先set，不然报错，收藏不好使


        Integer uid = WmThreadLocalUtils.getUser().getId();
        update(Wrappers.<WmMaterial>lambdaUpdate()
                .set(WmMaterial::getIsCollection,type)
                .eq(WmMaterial::getId,id)
                .eq(WmMaterial::getUserId,uid));

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
